<!--
 * @Author: cgl
 * @Date: 2023-04-18 15:12:26
 * @LastEditors: cgl
 * @LastEditTime: 2023-09-05 14:16:12
 * @FilePath: \public-health-emergencies-fed:\新放射\新radiation-hygiene-fe\src\views\slide\task.vue
 * @Description:
 *
 * Copyright (c) 2023 by cgl/微盛信息产业有限公司, All Rights Reserved.
-->
<template>
  <div class="app-container">
    <el-form
      class="searchform"
      :model="queryParams"
      ref="queryParams"
      size="small"
      label-width="80px"
    >
      <el-row :gutter="20">
        <el-col :span="5">
          <el-form-item label="单位名称" label-width="80px">
            <m-select
              v-model="queryParams.organizationName"
              placeholder="输入文字检索查询"
              style="width: 100%"
              filterable
              clearable
              :lists="entrustOrganizationSelect"
              lists_label="organizationName"
              lists_value="organizationName"
              lists_key="entrustOrganizationId"
              :total="orgTotal"
              :pageSize="10"
              @handleChange="listeningEvent"
            >
            </m-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="合同编号">
            <el-input
              v-model="queryParams.agreementNumber"
              placeholder="请输入"
              clearable
              @keyup.enter.native="getList()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="联系人">
            <el-input
              v-model="queryParams.contactsName"
              placeholder="请输入"
              clearable
              @keyup.enter.native="getList()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="是否收费">
            <el-select
              v-model="queryParams.charge"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                :label="item.label"
                :value="item.value"
                v-for="(item, index) in dict.type.is_or_no"
                :key="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label-width="20px">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="getList()"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="reset()"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="table-wrapper">
      <el-table
        v-loading="loading"
        :data="reportArchivingList"
        @row-dblclick="(row) => openhandleDialog(row, '3')"
      >
        <el-table-column label="序号" type="index" align="center" width="50">
          <template slot-scope="scope">
            <div style="text-align: center;">{{ scope.$index + 1 }}</div>
          </template>
        </el-table-column>
        <el-table-column
          label="合同编号"
          align="center"
          prop="agreementNumber"
        />
        <el-table-column label="是否收费" align="center" width="100">
          <template slot-scope="{ row }">
            <!-- <dict-tag
            :options="dict.type.is_or_no"
            :value="row.charge || 0"
          ></dict-tag> -->
            <span :style="{ color: row.charge == 1 ? '#67c23a' : 'red' }">{{
              row.charge == 1 ? "是" : "否"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="委托单位"
          align="center"
          prop="organizationName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="联系人"
          align="center"
          prop="contactsName"
          width="120"
        />
        <el-table-column
          label="联系电话"
          align="center"
          prop="contactsMobile"
          width="150"
        />
        <el-table-column
          label="单位地址"
          align="center"
          prop="organizationAddress"
          width="150"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="检测人员"
          align="center"
          prop="personNum"
          width="150"
        />
        <el-table-column label="录入时间" align="center" prop="createTime" />
        <el-table-column label="年份" align="center" prop="year" width="100" />
        <el-table-column
          label="批次"
          align="center"
          prop="batchNum"
          width="60"
        />
        <el-table-column align="center" label="操作">
          <template slot-scope="{ row }">
            <el-button
              v-if="activeName == '1' || activeName == '2'"
              @click.native.prevent="handleFlowRecord(row)"
              type="text"
            >
              流程
            </el-button>
            <el-button
              v-if="activeName == '2'"
              @click.native.prevent="viewFile(row, true)"
              type="text"
            >
              报告
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 办理弹框 -->
    <el-dialog
      :title="bltitle"
      :visible.sync="dialogVisiblehandle"
      :close-on-click-modal="false"
      width="1500px"
      class="bldialog"
      v-dialogDrag="true"
    >
      <el-form
        class="handleform"
        :disabled="blstatus != '1'"
        :model="handleform"
        size="small"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="单位名称">
              <el-input v-model="handleform.organizationName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同编号">
              <el-input
                v-if="handleform.agreementNumber"
                v-model="handleform.agreementNumber"
                disabled
              ></el-input>
              <el-select
                v-else
                v-model="handleform.agreementId"
                :placeholder="blstatus == '1' ? '请选择' : ''"
                style="width: 100%"
                clearable
              >
                <el-option
                  :label="item.agreementNumber"
                  :value="item.agreementId"
                  v-for="(item, index) in agreementList"
                  :key="index"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人">
              <el-input v-model="filterContact" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="联系电话">
              <el-input v-model="filterMobile" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="监测周期(天)">
              <el-input-number
                v-model="handleform.monitoringCycle"
                disabled
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="监测启用状态">
              <el-select
                v-model="handleform.monitoringState"
                disabled
                style="width: 100%"
              >
                <el-option
                  v-for="item in dict.type.status_disable"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="单位地址">
              <el-input v-model="handleform.organizationAddress" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="佩戴开始日期">
              <el-date-picker
                style="width: 100%"
                v-model="handleform.wearingBeginTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="date"
                :picker-options="pickerOptionsHandleF"
                placeholder="请选择"
                clearable
                @change="
                  (val) => handleChangeHandleWearTime(val, 'wearingEndTime')
                "
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="佩戴结束日期">
              <el-date-picker
                style="width: 100%"
                v-model="handleform.wearingEndTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="date"
                :picker-options="pickerOptionsHandleS"
                placeholder="请选择"
                clearable
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批次" prop="batchNum">
              <el-input
                v-model="handleform.batchNum"
                placeholder="请输入1 - 4批号"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="separate"></div>
      <el-form
        class="handleform"
        @submit.native.prevent
        :model="queryParamsHandle"
        size="small"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="关键词">
              <el-input
                v-model="queryParamsHandle.searchStr"
                placeholder="请输入人员编号、剂量计编号、人员姓名或部门"
                clearable
                @clear="getListHandle()"
                @keyup.enter.native="getListHandle()"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="20px">
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="getListHandle()"
                >查询</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="bloperation">
        <div class="filelist">
          查看文件：
          <span
            class="filelistitem"
            v-for="(item, index) in fileRecordList"
            :key="'record' + index"
            @click="viewFile(item)"
          >
            <!-- {{item.originalName}} -->
            记录
          </span>
          <span
            class="filelistitem"
            v-for="(item, index) in fileList"
            :key="index"
            @click="viewFile(item)"
          >
            <!-- {{item.originalName}} -->
            报告
          </span>
        </div>
        <el-button
          v-if="blstatus == '1'"
          class="blbutton"
          type="primary"
          :disabled="!handleform.list || handleform.list.length == 0"
          size="mini"
          @click.native.prevent="handleReport('record')"
          >生成记录</el-button
        >
        <el-button
          v-if="blstatus == '1'"
          class="blbutton"
          type="primary"
          :disabled="!handleform.list || handleform.list.length == 0"
          size="mini"
          @click.native.prevent="handleReport()"
          >生成报告</el-button
        >
        <el-popover placement="top" width="auto" trigger="hover">
          <el-button
            v-for="(item, index) in fileRecordList"
            :key="'record' + index"
            class="blbutton"
            type="primary"
            size="mini"
            @click.native.prevent="viewFile(item)"
            >打印原始记录</el-button
          >
          <el-button
            v-for="(item, index) in fileList"
            :key="index"
            class="blbutton"
            type="primary"
            size="mini"
            @click.native.prevent="viewFile(item)"
            >打印报告</el-button
          >
          <el-button
            v-if="blstatus == '1'"
            class="blbutton"
            type="primary"
            :disabled="!handleform.list || handleform.list.length == 0"
            size="mini"
            @click.native.prevent="handlePrint()"
            >打印编号</el-button
          >
          <el-button
            v-if="blstatus == '1'"
            type="primary"
            size="mini"
            @click.native.prevent="handlePrintTurnoverRegister()"
            >打印告知书</el-button
          >
          <el-button
            v-if="blstatus == '1'"
            type="primary"
            size="mini"
            @click.native.prevent="handlePrintTurnoverRegister()"
            >打印流转登记表</el-button
          >
          <el-button
            slot="reference"
            class="blbutton"
            type="primary"
            size="mini"
            >打印</el-button
          >
        </el-popover>
        <!-- <el-button v-if="blstatus == '1'" class="blbutton" type="primary" :disabled="!handleform.list || handleform.list.length == 0" size="mini" @click.native.prevent="handlePrint()">打印编号</el-button> -->
        <!-- <el-button v-if="blstatus == '1'" type="primary" size="mini" @click.native.prevent="handlePrintTurnoverRegister()">打印流转登记表</el-button> -->
      </div>
      <el-table
        class="handletabel"
        ref="tableData"
        :class="blstatus == '2' && 'handletabelaudit'"
        v-loading="loadingHandle"
        :data="handleform.list"
        :row-class-name="tableRowClassName"
        :cell-class-name="tableCellClassName"
        @selection-change="handleSelectionChange"
        height="356"
        @row-dblclick="dbclick"
      >
        <el-table-column
          type="selection"
          align="center"
          width="50"
          :selectable="selectable"
        />
        <el-table-column
          label="人员编号"
          align="center"
          prop="personnelNumber"
          width="100"
        />
        <el-table-column
          label="剂量计编号"
          align="center"
          prop="dosageNumber"
          width="120"
        />
        <el-table-column label="姓名" align="center" width="100">
          <template slot-scope="scope">
            <span>
              <span>{{ scope.row.personnelName }}</span>
              <span v-if="scope.row.dosageType == 1">(内)</span>
              <span v-if="scope.row.dosageType == 2">(外)</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="性别" align="center" width="80">
          <template slot-scope="scope">
            <dict-tag
              :value="scope.row.personnelSex"
              :options="dict.type.sys_user_sex"
            ></dict-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="职业类别"
          align="center"
          width="150"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <dict-tag
              :value="scope.row.occupationalClassification"
              :options="dict.type.occupational_classification"
            ></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="部门" align="center" prop="entrustDeptName" />
        <el-table-column label="剂量计佩戴起止日期" align="center" width="220">
          <template slot-scope="scope">
            <span>
              {{ parseTime(scope.row.wearingBeginTime, "{y}/{m}/{d}") }} -
              {{ parseTime(scope.row.wearingEndTime, "{y}/{m}/{d}") }}
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="寄出单号" align="center" prop="sendTrackingNumber" :width="blstatus != '3' && 130">
						<template slot-scope="scope">
							<span>
								<span>{{scope.row.sendTrackingNumber}}</span>
							</span>
						</template>
					</el-table-column> -->
        <el-table-column
          label="剂量当量1"
          align="center"
          prop="holeOneDosageValue"
          width="100"
        />
        <el-table-column
          label="剂量当量2"
          align="center"
          prop="holeTwoDosageValue"
          width="100"
        />
        <el-table-column
          label="剂量当量(mSv)"
          align="center"
          prop="dosageValue"
          width="120"
        />
      </el-table>

      <pagination
        style="margin-bottom: 5px"
        v-show="totalHandle > 0"
        :total="totalHandle"
        :page.sync="queryParamsHandle.pageNum"
        :limit.sync="queryParamsHandle.pageSize"
        @pagination="getListHandle"
      />

      <div slot="footer">
        <el-button
          v-if="blstatus == '1' || blstatus == '3'"
          @click="dialogVisiblehandle = false"
          >关 闭</el-button
        >
      </div>
    </el-dialog>

    <WorkFlow ref="workFlow"></WorkFlow>
    <batch-print ref="batchPrintRefs"></batch-print>
  </div>
</template>

<script>
import {
  personalDosimeterDetail,
  getHandleData,
  generateReport,
  getUnHandleWorkPersonnelList,
  genCirculationRegister,
  genDosageNotification,
} from "@/api/slides/task";
import { getReportArchivingList } from "@/api/slides/fileReport";
import { getConfiglargeDose } from "@/api/slides/abnormal";
import { getWaitSendPersonnelListByIds } from "@/api/slides/waitSend";
import { getAgreementListWithTaskDosimeter } from "@/api/person/entrustAgreement";
import {
  entrustOrganizationListing,
  entrustOrganizationList,
} from "@/api/person/entrustOrganization";
import { listByIds } from "@/api/system/oss";
import WorkFlow from "@/components/WorkFlow";
import { getLodop, needCLodop } from "@/utils/LodopFuncs.js";
import MSelect from "@/components/mSelect";
import BatchPrint from "./waitSend.vue";
import { getToken } from "@/utils/auth";
import { blobToBase64 } from "@/utils/file";
import { parseTime } from "@/utils/ruoyi";

export default {
  name: "FileReport",
  dicts: [
    "status_disable",
    "is_or_no",
    "sys_user_sex",
    "occupational_classification",
  ],
  components: { MSelect, WorkFlow, BatchPrint },
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tasksState: "2",
      },
      total: 0,
      dialogVisible: false,
      // 表单参数
      form: {},
      loading: false,
      status: null,
      title: null,
      // 外照射任务列表
      reportArchivingList: [],
      // 办理弹框
      dialogVisiblehandle: false,
      handleStatus: null,
      handleform: {},
      blstatus: null,
      bltitle: null,
      // 合同下拉框
      agreementList: [],
      tableList: [], // 打印的标签集合
      nubId: [], // 标签顶部的条形码数据
      printOptions: [], // 打印机数据
      printType: "", // label1 -> 4*6; A4 -> A4
      LODOP: null,
      printList: [],
      // 办理的查询参数
      queryParamsHandle: {
        pageNum: 1,
        pageSize: 10,
        searchStr: "",
      },
      totalHandle: 0,
      // 打开的当行id
      handleId: null,
      loadingHandle: false,
      // 添加的查询参数
      queryParamsAdd: {
        pageNum: 1,
        pageSize: 10,
      },
      // 委托单位下拉框
      entrustOrganizationSelect: [],
      activeName: 2,
      totalAdd: 0,
      // 打开的当行id
      addId: null,
      loadingAdd: false,
      isPer: false,
      isHide: false,
      // 日期校验
      pickerOptionsF: {
        // disabledDate: (time) => {
        //   return time.getTime() > new Date(this.form.wearingEndTime).getTime();
        // },
      },
      pickerOptionsS: {
        // disabledDate: (time) => {
        //   return time.getTime() < new Date(this.form.wearingBeginTime).getTime();
        // },
      },
      pickerOptionsHandleF: {
        // disabledDate: (time) => {
        //   return time.getTime() > new Date(this.handleform.wearingEndTime).getTime();
        // },
      },
      pickerOptionsHandleS: {
        // disabledDate: (time) => {
        //   return time.getTime() < new Date(this.handleform.wearingBeginTime).getTime();
        // },
      },
      // 生成的报告列表
      fileList: [],
      // 勾选的打印列表
      selected: [],
      // 双击索引
      currentCell: null,
      // 未办理人员列表添行
      unHandleWorkPersonnelList: [],
      // 视图高度
      height: document.documentElement.clientHeight,
      // 修改快递单号
      editTrackingNumberVisible: false,
      editTrackingNumberForm: {},
      rulesTracking: {
        // sendTrackingNumber: [
        //   { required: true, message: "快递单号不能为空", trigger: "blur" },
        // ],
      },
      // 大剂量标准值
      largeDose: null,
      openRowHandle: {},
      isLaboratory: false,
      // 单位查询数据
      organizationQueryData: {
        organizationName: "", //单位名称模糊查询
        pageNum: 1, //页码
        pageSize: 10, //每页展示的条数
      },
      orgTotal: 0,
      fileRecordList: [],
      isPdf: "1",
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken(),
          "Content-Disposition": "inline",
        },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/oss/upload",
      },
      uploadFileList: [],
      uploadRecordFileList: [],
      manageForm: {},
      manageVisible: false,
    };
  },
  computed: {
    filterContact() {
      return this.handleform.dosageContactsName || this.handleform.contactsName;
    },
    filterMobile() {
      return (
        this.handleform.dosageContactsMobile || this.handleform.contactsMobile
      );
    },
  },
  created() {
    // 获取列表
    this.getList();
    // 获取大剂量标准值
    this.configlargeDose();
  },
  methods: {
    // 批量打印
    openPrintDialog() {
      // console.log(this.$refs.batchPrintRefs);
      this.$refs.batchPrintRefs.openDialog();
    },
    // 查看流程
    handleFlowRecord(row) {
      this.$refs.workFlow.openDialog(row);
    },
    // 异常的不允许勾选
    selectable(row, rowIndex) {
      if (
        (this.largeDose && row.dosageValue > this.largeDose) ||
        row.exceptional
      ) {
        return false;
      } else {
        return true;
      }
    },
    // 获取外照射任务列表
    getList() {
      this.loading = true;
      getReportArchivingList(this.queryParams)
        .then((response) => {
          this.reportArchivingList = response.rows || [];
          this.total = response.total;
          this.loading = false;
        })
        .catch((response) => {
          this.loading = false;
        });
    },
    // 获取单位下拉框
    listeningEvent(e) {
      let { queryName, pageNum, pageSize, type } = e;
      if (type == "scroll" && pageNum == this.organizationQueryData.pageNum)
        return;
      this.organizationQueryData.organizationName = queryName;
      this.organizationQueryData.pageNum = pageNum;
      this.organizationQueryData.pageSize = pageSize;
      entrustOrganizationList(this.organizationQueryData).then((response) => {
        if (type == "scroll") {
          this.entrustOrganizationSelect.push(...response.rows);
        } else {
          this.entrustOrganizationSelect = response.rows;
        }
        this.orgTotal = response.total;
      });
    },
    // 获取大剂量标准值
    configlargeDose() {
      getConfiglargeDose().then((response) => {
        this.largeDose = response.msg;
      });
    },
    // 列表标红
    tableRowClassName({ row, rowIndex }) {
      if (
        (this.largeDose && row.dosageValue > this.largeDose) ||
        row.exceptional
      ) {
        return "warning-row";
      }
      return "";
    },
    // 打开任务对话框
    openDialog() {
      this.form = {
        taskPersonalDosimeterResultList: [],
      };
      this.agreementList = [];
      this.resetForm("form");
      this.deletePerson = [];
      this.status = "1";
      this.title = "添加外照射任务";
      this.dialogVisible = true;
    },
    handleChangeHandleWearTime(val, timeTips) {
      const date = new Date(val);
      date.setDate(date.getDate() + 90);
      let newDate = parseTime(date, "{y}-{m}-{d} {h}:{i}:{s}");
      this.$set(this.handleform, timeTips, newDate);
    },
    // 打开办理对话框
    openhandleDialog(row, status) {
      this.handleform = {};
      this.fileList = [];
      this.fileRecordList = [];
      this.selected = [];
      this.currentCell = null;
      this.handleStatus = status;
      this.openRowHandle = row;
      this.handleform.taskPersonalDosimeterId = row.taskPersonalDosimeterId;
      this.uploadFileList = [];
      this.uploadRecordFileList = [];
      this.isPdf = "1";
      if (status == "1") {
        if (this.activeName == "1") {
          this.blstatus = "2";
        } else {
          this.blstatus = "1";
        }
        this.bltitle = "办理";
      }
      if (status == "3") {
        this.blstatus = "3";
        this.bltitle = "查看外照射任务";
      }
      personalDosimeterDetail(row.taskPersonalDosimeterId).then((response) => {
        if (response.data) {
          if (response.data.monitoringState != null) {
            response.data.monitoringState =
              response.data.monitoringState.toString();
          }
          this.handleform = response.data;
          this.handleform.operationList = [];
          if (response.data.entrustOrganizationId && status == "1") {
            getAgreementListWithTaskDosimeter({
              entrustOrganizationId: response.data.entrustOrganizationId,
            }).then((response) => {
              this.agreementList = response.data;
            });
          }
          if (response.data.ossId) {
            listByIds(response.data.ossId).then((response) => {
              this.fileList = response.data.map((item) => {
                return {
                  url: item.url,
                  originalName: item.originalName,
                };
              });
            });
          }
          if (response.data.recordOssId) {
            listByIds(response.data.recordOssId).then((response) => {
              this.fileRecordList = response.data.map((item) => {
                return {
                  url: item.url,
                  originalName: item.originalName,
                };
              });
            });
          }
          this.handleId = row.taskPersonalDosimeterId;
          this.queryParamsHandle = {
            pageNum: 1,
            pageSize: 10,
            searchStr: "",
          };
          this.getListHandle();
          this.dialogVisiblehandle = true;
        }
      });
      // 获取未办理人员下拉框
      getUnHandleWorkPersonnelList(row.taskPersonalDosimeterId).then(
        (response) => {
          // if(response.data && response.data.length != 0) {
          this.unHandleWorkPersonnelList = response.data || [];
          this.unHandleWorkPersonnelList.forEach((item) => {
            item.showTypeName =
              item.personnelName +
              (item.dosageType == "1"
                ? "(内)"
                : item.dosageType == "2"
                ? "(外)"
                : "");
            item.originName = item.personnelName;
            item.isEmptyTrackingNumber = !item.sendTrackingNumber;
          });
          // }
        }
      );
    },
    // 分页获取人员（根据row.taskPersonalDosimeterId）
    getListHandle() {
      this.queryParamsHandle.id = this.handleId;
      this.loadingHandle = true;
      getHandleData(this.queryParamsHandle)
        .then((response) => {
          this.handleform.list = response.rows || [];
          if (this.handleform.list.length != 0) {
            this.handleform.list.forEach((item) => {
              item.showTypeName =
                item.personnelName +
                (item.dosageType == "1"
                  ? "(内)"
                  : item.dosageType == "2"
                  ? "(外)"
                  : "");
              item.originName = item.personnelName;
              item.isEmptyTrackingNumber = !item.sendTrackingNumber;
            });
          }
          this.totalHandle = response.total;
          this.loadingHandle = false;
        })
        .catch((response) => {
          this.loadingHandle = false;
        });
    },
    // 生成报告
    handleReport(type = "report") {
      generateReport(
        this.handleform.taskPersonalDosimeterId,
        this.isPdf,
        type
      ).then((response) => {
        if (response.msg) {
          /* 生成错误 */
          this.$alert(
            "<div style='overflow: auto; max-height: 70vh; padding: 0 20px 0; margin-top: -20px;'>" +
              response.msg +
              "</div>",
            "生成失败",
            { dangerouslyUseHTMLString: true }
          );
        } else {
          if (response.data) {
            this.$alert(
              "<div style='overflow: auto; max-height: 70vh; padding: 0 20px 0; font-size: 16px'>" +
                "生成成功！" +
                "</div>",
              "",
              { dangerouslyUseHTMLString: true }
            );
            listByIds(response.data).then((response) => {
              this.fileList = response.data.map((item) => {
                return {
                  url: item.url,
                  originalName: item.originalName,
                };
              });
            });
          }
        }
        personalDosimeterDetail(
          this.openRowHandle.taskPersonalDosimeterId
        ).then((response) => {
          this.handleform.isReport = response.data?.isReport; /* 更新isReport */
          this.handleform.recordReportState = response.data?.recordReportState;
          if (response.data?.ossId) {
            /* 更新生成报告 */
            listByIds(response.data.ossId).then((response) => {
              this.fileList = response.data.map((item) => {
                return {
                  url: item.url,
                  originalName: item.originalName,
                };
              });
            });
          }
          if (response.data?.recordOssId) {
            /* 更新生成报告 */
            listByIds(response.data.recordOssId).then((response) => {
              this.fileRecordList = response.data.map((item) => {
                return {
                  url: item.url,
                  originalName: item.originalName,
                };
              });
            });
          }
        });
      });
    },
    // 报告预览
    viewFile(item, isTable) {
      if (isTable) {
        /* 已签发列表打开 */
        if (item.ossId) {
          listByIds(item.ossId).then((response) => {
            window.open(response?.data[0]?.url, "PDF", "");
          });
        } else {
          this.$modal.msgWarning("暂无文件");
        }
      } else {
        if (item && item.url) {
          window.open(item.url, "PDF", "");
        } else {
          this.$modal.msgWarning("暂无文件");
        }
      }
    },
    // 流转登记表
    handlePrintTurnoverRegister() {
      let LODOP = getLodop();
      LODOP.PRINT_INIT("流转登记表");
      LODOP.SET_PRINT_PAGESIZE(1, 0, 0, "A4");
      genCirculationRegister(this.handleform.taskPersonalDosimeterId).then(
        (response) => {
          // console.log(response);
          // listByIds(res.data).then((response) => {
          // 	window.open(response.data[0].url, 'pdf')
          // });
          let binaryData = [];
          binaryData.push(response.data);
          blobToBase64(new Blob(binaryData, { type: "application/pdf" })).then(
            (res) => {
              LODOP.ADD_PRINT_PDF(
                "0",
                "0",
                "100%",
                "100%",
                res.split("data:application/pdf;base64,")[1]
              );
              // console.log(res);
              // 设置对后台打印状态进行捕获
              LODOP.SET_PRINT_MODE("CATCH_PRINT_STATUS", true);
              // LODOP.PRINT();
              LODOP.PREVIEW(); // 预览
            }
          );
        }
      );
    },
    // 告知书
    handlePrintTurnoverRegister() {
      let LODOP = getLodop();
      LODOP.PRINT_INIT("告知书");
      LODOP.SET_PRINT_PAGESIZE(1, 0, 0, "A4");
      genDosageNotification(this.handleform.taskPersonalDosimeterId).then(
        (response) => {
          // console.log(response);
          // listByIds(res.data).then((response) => {
          // 	window.open(response.data[0].url, 'pdf')
          // });
          let binaryData = [];
          binaryData.push(response.data);
          blobToBase64(new Blob(binaryData, { type: "application/pdf" })).then(
            (res) => {
              LODOP.ADD_PRINT_PDF(
                "0",
                "0",
                "100%",
                "100%",
                res.split("data:application/pdf;base64,")[1]
              );
              // console.log(res);
              // 设置对后台打印状态进行捕获
              LODOP.SET_PRINT_MODE("CATCH_PRINT_STATUS", true);
              // LODOP.PRINT();
              LODOP.PREVIEW(); // 预览
            }
          );
        }
      );
    },
    // 查询重置
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        tasksState: this.isPer ? "-4" : "-3",
      };
      this.resetForm("queryParams");
      this.getList();
    },
    // 更改打印勾选
    handleSelectionChange(selection) {
      this.selected = selection;
    },
    // 打印编号
    async handlePrint() {
      let printList = [];
      if (this.selected.length == 0) {
        // printList = JSON.parse(JSON.stringify(this.handleform.list)); // 当前页数
        let { code, data } = await getWaitSendPersonnelListByIds({
          dosimeterIds: this.handleform.taskPersonalDosimeterId,
          isFilter: 0,
        });
        printList = data || [];
      } else {
        printList = this.selected;
      }
      if (needCLodop()) {
        try {
          let LODOP = getLodop();
          console.log("LODOP", LODOP);

          console.log("---------", LODOP.GET_PRINTER_NAME(0));
          console.log("---------", LODOP.GET_PRINTER_NAME(1));
          console.log("---------", LODOP.GET_PRINTER_COUNT());
          console.log(
            "---------PaperLength",
            LODOP.GET_PRINTER_NAME("0:PaperLength")
          );
          console.log(
            "---------PaperWidth",
            LODOP.GET_PRINTER_NAME("0:PaperWidth")
          );
          console.log(
            "---------MaxExtentWidth",
            LODOP.GET_PRINTER_NAME("0:MaxExtentWidth")
          );
          console.log(
            "---------PaperSize",
            LODOP.GET_PRINTER_NAME("0:PaperSize")
          );
          console.log(
            "---------PortName",
            LODOP.GET_PRINTER_NAME("0:PortName")
          );
          console.log(
            "---------MinExtentWidth",
            LODOP.GET_PRINTER_NAME("0:MinExtentWidth")
          );
          console.log("---------Copies", LODOP.GET_PRINTER_NAME("0:Copies"));
          // console.log("---------", LODOP.GET_PRINTER_NAME("1:MaxExtentWidth"));
          this.loading = true;
          if (true) {
            /* 演示-芯烨打印机 */
            let num = Math.ceil(printList.length / 2);
            LODOP.SET_PRINT_PAGESIZE(1, `7.8cm`, `${18}mm`, "");
            LODOP.SET_PRINT_MODE("POS_BASEON_PAPER", true);
            printList.forEach((item, index) => {
              // 设置每两条数据创建纸张
              let xStandard = index % 2 == 0 ? 0 : 40; // 纸张x轴
              let yMultiple = Math.ceil((index + 1) / 2); // 行数倍率
              let yStandard = 0; // y轴偏移量
              // let yStandard = (yMultiple - 1) * 20 // y轴偏移量
              console.log(xStandard, yStandard);

              let offset = xStandard; /* 水平便宜量 */
              let offsetOri = yStandard; /* 垂直偏移量 */
              // 委托单位------------------------------------
              item.entrustOrganizationName =
                item.entrustOrganizationName?.length > 14
                  ? item.entrustOrganizationName.slice(0, 13) + "..."
                  : item.entrustOrganizationName;
              LODOP.ADD_PRINT_TEXT(
                `${2 + offsetOri}mm`,
                `${2 + offset}mm`,
                "100%",
                "100%",
                item.entrustOrganizationName || ""
              );
              // LODOP.SET_PRINT_STYLEA(0, "FontSize", );
              LODOP.SET_PRINT_STYLEA(0, "FontSize", 7);
              LODOP.SET_PRINT_STYLEA(0, "Bold", 1);
              // // 部门-------------------------------------
              // LODOP.ADD_PRINT_TEXT(`${6 + offsetOri}mm`, `${2 + offset}mm`,"100%","100%", item.entrustDeptName || "");
              // LODOP.SET_PRINT_STYLEA(0, "FontSize", 8);
              // LODOP.SET_PRINT_STYLEA(0, "Bold" , 1);
              // // 铅衣--------------------------------------
              // if(item.personnelName == "环境对照") {
              // 	LODOP.ADD_PRINT_TEXT(`${11 + offsetOri}mm`, `${2 + offset}mm`,"100%","100%", "");
              // }else {
              // 	LODOP.ADD_PRINT_TEXT(`${11 + offsetOri}mm`, `${2 + offset}mm`, "100%","100%",
              // 		`${item.dosageType == "1" ? '铅衣内' :
              // 		item.dosageType == "2" ? '铅衣外' :
              // 		item.dosageType == "3" ? '本底' : ''}`);
              // }
              // LODOP.SET_PRINT_STYLEA(0, "FontSize", 8);
              // LODOP.SET_PRINT_STYLEA(0, "Bold" , 1);
              // 二维码---------------------------------------------
              LODOP.ADD_PRINT_BARCODE(
                `${6 + offsetOri}mm`,
                `${16 + offset}mm`,
                "18mm",
                "8mm",
                "128Auto",
                item.dosageNumber + "-" + item.batchNum
              );
              LODOP.SET_PRINT_STYLEA(0, "FontSize", 6);
              // 姓名------------------------------------
              LODOP.ADD_PRINT_TEXT(
                `${6 + offsetOri}mm`,
                `${2 + offset}mm`,
                "100%",
                "100%",
                `${item.personnelName || ""}` +
                  `${
                    item.dosageType == "1"
                      ? "(内)"
                      : item.dosageType == "2"
                      ? "(外)"
                      : ""
                  }`
              );
              LODOP.SET_PRINT_STYLEA(0, "FontSize", 8);
              LODOP.SET_PRINT_STYLEA(0, "Bold", 1);

              // 科室------------------------------------
              LODOP.ADD_PRINT_TEXT(
                `${10 + offsetOri}mm`,
                `${2 + offset}mm`,
                "100%",
                "100%",
                `${item.entrustDeptName || ""}`
              );
              LODOP.SET_PRINT_STYLEA(0, "FontSize", 8);
              LODOP.SET_PRINT_STYLEA(0, "Bold", 1);

              // 时间------------------------------------
              LODOP.ADD_PRINT_TEXT(
                `${14 + offsetOri}mm`,
                `${2 + offset}mm`,
                "100%",
                "100%",
                `${this.parseTime(
                  item.wearingBeginTime,
                  "{y}/{m}/{d}"
                )}-${this.parseTime(item.wearingEndTime, "{y}/{m}/{d}")}`
              );
              LODOP.SET_PRINT_STYLEA(0, "FontSize", 6);
              LODOP.SET_PRINT_STYLEA(0, "Bold", 1);
              if (index % 2 == 1) {
                LODOP.NEWPAGE();
              }
            });
            // LODOP.NEWPAGE();
          }
          // LODOP.PRINT();
          LODOP.PREVIEW();
          this.loading = false;
        } catch (error) {
          console.log("error", error);
          this.$alert(
            `检测到您还未安装C-LODOP套打控件,请确认启用后再打印。或您可点击下载该套打控件，安装成功后刷新页面再进行打印`,
            "提示",
            {
              confirmButtonText: "确定",
              callback: (action) => {
                window.open("https://www.lodop.net/download.html");
              },
            }
          );
        }
      }
    },
    // 给单元格绑定横向和竖向的index，这样就能确定是哪一个单元格
    tableCellClassName({ row, column, rowIndex, columnIndex }) {
      row.index = rowIndex;
      column.index = columnIndex;
    },
    // 获得当前双击的单元格的横竖index，然后拼接成一个唯一字符串用于判断，并赋给currentCell
    // 拼接后类似这样："1,0","1,1",
    dbclick(row, column) {
      if (this.handleStatus == "3") return;
      console.log("双击", row, column);
      this.currentCell = row.index + "," + column.index;
      // 这里必须要setTimeout，因为在点击的时候，input才刚被v-if显示出来，不然拿不到dom
      setTimeout(() => {
        // 双击后自动获得焦点
        if (this.$refs[row.index + "," + column.index]) {
          this.$refs[row.index + "," + column.index].focus();
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;
}

.uploadbutton {
  padding-inline: 20px;
}
.myupload {
  margin-bottom: 20px;
}
.result {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 30px;
  .calc {
    width: min-content;
    margin-left: 20px;
    .el-button {
      margin: 0;
      &:nth-of-type(1) {
        margin-bottom: 10px;
      }
    }
  }
}
.nametitle {
  text-align: center;
  margin-bottom: 10px;
  font-weight: bolder;
  &::before {
    content: "* ";
    color: red;
  }
}
::v-deep .el-table .warning-row {
  color: red;
}
.searchcontainer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: -10px;
}
.viewform {
  justify-content: flex-end;
}
.title {
  padding-left: 10px;
  border-left: 5px solid #2a72ee;
  text-align: left;
  font-weight: bolder;
  font-size: 16px;
  margin-bottom: 30px;
}
.operation {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  .editform {
    .el-form-item {
      margin-bottom: 0;
    }
  }
}
.bloperation {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
  .filelist {
    margin: 0 auto 0 0;
    margin-left: 30px;
    margin-right: 30px;
    font-weight: bolder;
    .filelistitem {
      color: #2a72ee;
      cursor: pointer;
      &:hover {
        color: #2a72ee;
        text-decoration: underline;
      }
    }
  }
  .docupload {
    display: flex;
    margin-right: auto;
    // width: 500px;
    > * {
      margin-right: 12px;
      &:last-child {
        margin-right: 0;
      }
    }
    ::v-deep .el-upload-list {
      max-width: 300px;
      .el-upload-list__item {
        margin-top: 3px;
        .el-icon-close-tip {
          display: none;
        }
      }
    }
  }
  .type {
    margin-right: 20px;
  }
  .blbutton {
    margin-right: 20px;
  }
}
.codecontainer {
  width: 5cm;
  height: 10cm;
  .item {
    color: red;
    font-size: 12px;
  }
}
// 生成图片样式
.printmy {
  position: relative;
  font-size: 10px;
  background-color: aqua;
  width: 50mm;
  height: 23mm;
  margin-bottom: 5mm;
  padding: 2mm;
  .barcode {
    position: absolute;
    top: 2mm;
    right: 3mm;
  }
}
::v-deep .handletabel.el-table {
  margin-bottom: 60px;
  overflow: auto;
  .el-table__body-wrapper {
    overflow-y: auto;
    overflow-x: hidden;
  }
}
.flowdialog .el-tabs {
  height: 700px;
  overflow: auto;
}
.blbtn {
  margin-right: 50px;
}
.bldialog ::v-deep .el-dialog {
  max-height: 95%;
  .el-dialog__body {
    position: relative;
  }
}
.addtask ::v-deep .el-dialog__body {
  position: relative;
}
.wearingedit ::v-deep .el-input__inner {
  padding-right: 0;
}
.selectperson ::v-deep .el-input__inner {
  padding-right: 7px;
}
.separate {
  width: 100%;
  height: 1px;
  background-color: #d2d2d2;
  margin-bottom: 15px;
}
::v-deep .el-button.ovbutton {
  padding-block: 0;
}
::v-deep .tab {
  margin-top: -10px;
}
</style>
